<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i>设备固件管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!--新增-->
        <el-row class="container">
            <el-col :span="12">
                <div class="panel-body">
                    <el-form :label-position="'right'" label-width="80px" ref="addData" :model="addData"
                             :rules="addRules">
                        <el-form-item label="版本号" prop="version">
                            <el-input v-model="addData.version" maxlength="30" placeholder="V1.0"></el-input>
                        </el-form-item>
                        <el-form-item label="升级类型" prop="strategy">
                            <el-select add-select v-model="addData.strategy">
                                <el-option v-for="(key,value) in typeMap" :label="key" :value="value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="固件文件" prop="romFile">
                            <input type="file" @change="handleFileChange($event, 'romFile')">
                            <span>{{romSize}}</span>
                        </el-form-item>
                        <el-form-item label="上传进度">
                            <el-progress :text-inside="true" :stroke-width="25"
                                         :percentage="uploadPercent"></el-progress>
                        </el-form-item>
                        <el-form-item style="text-align:left">
                            <el-button type="primary" @click="submitForm('addData')" class="yes-btn">确 定</el-button>
                            <el-button @click="resetForm('addData')">重 置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
        </el-row>
        <el-row class="container">
            <el-col :span="24">
                <el-table :data="tableData" border class="table">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column align="left" label="固件名称" prop="fileName"></el-table-column>
                    <el-table-column align="left" label="版本号" prop="version"></el-table-column>
                    <el-table-column align="left" label="大小" prop="size"></el-table-column>

                    <el-table-column
                            :formatter="formatType"
                            label="升级策略"
                            prop="strategy">
                    </el-table-column>

                    <el-table-column
                            :formatter="formatDate"
                            label="创建时间"
                            prop="createTime">
                        <template slot-scope="scope">
                            <i class="el-icon-time">{{formatTimeDate(scope.row.createTime)}}</i>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="180" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑
                            </el-button>
                            <el-button type="text" icon="el-icon-delete" class="red"
                                       @click="handleDelete(scope.$index, scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑APP版本信息" :visible.sync="editVisible" width="30%">
            <el-form ref="editFormData" :model="editFormData" :rules="editRules" label-width="80px">
                <el-form-item label="版本号" prop="version">
                    <el-input v-model="editFormData.version"></el-input>
                </el-form-item>
                <el-form-item label="升级类型">
                    <el-select edit-select v-model="editFormData.strategy" placeholder="请选择模型类型">
                        <el-option v-for="(key,value) in typeMap" :label="key" :value="value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="text-align:left">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit('editFormData')">确 定</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>
    </div>
</template>

<script>
    import DateUtil from "@/common/DateUtil"
    import HttpUtil from "@/common/HttpUtil"

    export default {
        name: "FirmwareMgr",
        data() {
            return {
                optIndex: 0,//编辑行索引
                editVisible: false,//编辑框开关
                tableData: [],//table数据
                addData: {version: "", strategy: "SUGGESTED_UPDATE", romFile: null},//新增数据
                romSize: "",
                uploadPercent: 0,//上传进度
                editFormData: {version: "", strategy: ""},//编辑数据
                typeMap: {//类型转换
                    SUGGESTED_UPDATE: "建议升级",
                    FORCE_UPDATE: "强制升级"
                },
                addRules: {//新增校验规则
                    version: [{required: true, message: '版本号不能为空', trigger: 'blur'}],
                    romFile: [{required: true, message: 'ROM文件不能为空', trigger: 'blur'}],
                    strategy: [{required: true, message: '类型不能为空', trigger: 'blur'}],
                },
                editRules: {//编辑校验规则
                    version: [{required: true, message: '版本号不能为空', trigger: 'blur'}]
                }
            }
        },
        mounted() {
            this.initData();
        },
        methods: {
            initData() {
                let self = this
                let pageSize = self.curPageSize
                this.$axios.get("/app/v1/firm-versions").then(function (response) {
                    self.tableData = response.data.entity;
                }).catch(function (error) {
                    self.$message.warning("请求设备固件数据失败")
                });
            },
            //时间格式化函数
            formatDate: DateUtil.formatDate,
            formatTimeDate: DateUtil.formatTimeDate,
            //类型转换函数
            formatType: function (row, column) {
                return this.typeMap[row.strategy]
            },
            //新增提交
            submitForm(formName) {
                let self = this
                self.uploadPercent = 0
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let config = HttpUtil.getMultiPostConfig(function (val) {
                            self.uploadPercent = val
                        })
                        let formData = new FormData();
                        formData.append("version", self.addData.version)
                        formData.append("strategy", self.addData.strategy)
                        formData.append("firmFile", self.addData.romFile)
                        this.$axios.post("/admin/add-firm-version", formData, config).then(function (response) {
                            self.uploadPercent = 100;
                            self.initData()
                            self.$message.success('添加固件成功')
                        }).catch(function (error) {
                            self.$message.error('添加固件失败')
                            HttpUtil.checkHttpErr(error)
                        });
                    }
                });
            },
            //新增重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //编辑事件
            handleEdit(index, row) {
                this.optIndex = index;
                let item = this.tableData[index];
                this.editFormData.version = item.version
                this.editFormData.strategy = item.strategy
                this.editVisible = true;
            },
            //删除事件
            handleDelete(index, row) {
                let self = this
                this.optIndex = index;
                let id = this.tableData[index].id
                this.$confirm('删除不可恢复，是否确定删除?', '删除确认', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post("/admin/delete-firm-version/" + id).then(function (response) {
                        self.tableData.splice(self.optIndex, 1)
                        self.$message.success('删除成功')
                    }).catch(function (error) {
                        self.$message.error('删除失败');
                        HttpUtil.checkHttpErr(error)
                    })
                }).catch(() => {
                    //取消删除
                });
            },
            // 保存编辑
            saveEdit(formName) {
                let self = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        self.$message.warning("此功能暂未开放");
                    } else {
                        //校验不通过
                    }
                });
            },
            //文件选择
            handleFileChange(event, type) {
                let file = event.target.files[0]
                this.addData[type] = file
                this.romSize = DateUtil.getFileSize(file.size)
            },
        }
    }
</script>

<style scoped>
    .el-input, .el-select, .el-progress {
        width: 90%;
    }

    input[type='file'] {
        padding: 5px;
        background-color: gainsboro;
        border-radius: 5px;
        width: 87%;
    }
</style>